matplotlib.pyplot.boxplot()
import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)
# fake up some data
spread = np.random.rand(50) * 100
center = np.ones(25) * 50
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
data = np.concatenate((spread, center, flier_high, flier_low))
fig1, ax1 = plt.subplots()
ax1.set_title('Basic Plot')
ax1.boxplot(data)
{'whiskers': [<matplotlib.lines.Line2D at 0x2bb94952610>,
<matplotlib.lines.Line2D at 0x2bb949528e0>],
'caps': [<matplotlib.lines.Line2D at 0x2bb94952bb0>,
<matplotlib.lines.Line2D at 0x2bb94952e80>],
'boxes': [<matplotlib.lines.Line2D at 0x2bb94952310>],
'medians': [<matplotlib.lines.Line2D at 0x2bb94960190>],
'fliers': [<matplotlib.lines.Line2D at 0x2bb94960460>],
'means': []}
#hiển thị khoảng tin cậy xung quanh trung bình thường dựa trên trung vị +/- 1,57 x IQR / sqrt của n
fig2, ax2 = plt.subplots()
ax2.set_title('Notched boxes')
ax2.boxplot(data, notch=True)
{'whiskers': [<matplotlib.lines.Line2D at 0x2bb949c5250>,
<matplotlib.lines.Line2D at 0x2bb949c5520>],
'caps': [<matplotlib.lines.Line2D at 0x2bb949c57f0>,
<matplotlib.lines.Line2D at 0x2bb949c5ac0>],
'boxes': [<matplotlib.lines.Line2D at 0x2bb949b4f10>],
'medians': [<matplotlib.lines.Line2D at 0x2bb949c5d90>],
'fliers': [<matplotlib.lines.Line2D at 0x2bb949d00a0>],
'means': []}
matplotlib.pyplot.hist ()
Đây là một đại diện biểu đồ của một phân bố tần suất của một số dữ liệu số. Hình chữ nhật có kích thước bằng nhau theo chiều ngang có chiều cao tương ứng với tần suất.
#Ví dụ sau vẽ biểu đồ về điểm của các sinh viên trong một lớp học. Bốn cột, 0-25, 26-50, 51-75 và 76-100
# Add the essential library
import matplotlib.pyplot as plt
# Create the data
employee_age = [21,28,32,34,35,35,37,42,47,55]
# Create bins for histogram
bins = [20,30,40,50,60]
# Plot the histogramData Visualization Chapter 5
[ 145 ]
plt.hist(employee_age, bins, rwidth=0.6)
# Add X Label on X-axis
plt.xlabel("Employee Age")
# Add X Label on X-axis
plt.ylabel("Frequency")
# Add title to graph
plt.title("Employee Age Distribution")
# Show the plot
plt.show()
seaborn.heatmap ()
Bản đồ nhiệt được định nghĩa là một biểu diễn đồ họa của dữ liệu sử dụng màu sắc để trực quan hóa giá trị của ma trận.
Heat Maps thể hiện các giá trị phổ biến hơn hoặc các hoạt động cao hơn, màu sáng hơn về cơ bản được sử dụng và để đại diện cho các giá trị hoạt động hoặc ít phổ biến hơn, màu tối hơn được ưu tiên!
Sự khác biệt trong cách thể hiện màu sắc này giúp người xem dễ dàng hiểu được xu hướng nhanh chóng hơn.
Nó có lợi cho hai mục đích chính:
# Import required library
import seaborn as sns
# Read iris data using load_dataset() function
data = sns.load_dataset("iris")
# Find correlationData Visualization Chapter 5
[ 163 ]
cor_matrix=data.corr()
# Create heatmap
sns.heatmap(cor_matrix, annot=True)
# Show figure
plt.show()
# Create heatmap
sns.heatmap(cor_matrix, annot=True, cmap="YlGnBu")
# Show figure
plt.show()
#Số lượng sinh viên đăng ký cho các khóa học khác nhau được cung cấp tại một viện.
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
ax.bar(langs,students)
plt.show()
#Đối tượng dữ liệu là một số lượng sinh viên đã đậu vào ba ngành của một trường cao đẳng kỹ thuật trong bốn năm qua.
import numpy as np
import matplotlib.pyplot as plt
data = [[30, 25, 50, 20],
[40, 23, 51, 17],
[35, 22, 45, 19]]
X = np.arange(4)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.bar(X + 0.00, data[0], color = 'b', width = 0.25)
ax.bar(X + 0.25, data[1], color = 'g', width = 0.25)
ax.bar(X + 0.50, data[2], color = 'r', width = 0.25)
<BarContainer object of 4 artists>
import matplotlib.pyplot as plt
Year = [1920,1930,1940,1950,1960,1970,1980,1990,2000,2010]
Unemployment_Rate = [9.8,12,8,7.2,6.9,7,6.5,6.2,5.5,6.3]
plt.plot(Year, Unemployment_Rate)
plt.title('Unemployment Rate Vs Year')
plt.xlabel('Year')
plt.ylabel('Unemployment Rate')
plt.show()
import matplotlib.pyplot as plt
Year = [1920,1930,1940,1950,1960,1970,1980,1990,2000,2010]
Unemployment_Rate = [9.8,12,8,7.2,6.9,7,6.5,6.2,5.5,6.3]
plt.plot(Year, Unemployment_Rate, color='red', marker='o')
plt.title('Unemployment Rate Vs Year', fontsize=14)
plt.xlabel('Year', fontsize=14)
plt.ylabel('Unemployment Rate', fontsize=14)
plt.grid(True)
plt.show()
#biểu đồ hình tròn của danh sách sinh viên đăng ký các khóa học ngôn ngữ máy tính khác nhau
from matplotlib import pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.axis('equal')
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
ax.pie(students, labels = langs,autopct='%1.2f%%')
plt.show()
Biểu đồ phân tán vẽ các điểm dữ liệu bằng cách sử dụng tọa độ Descartes để hiển thị giá trị của các giá trị số. Chúng cũng đại diện cho mối quan hệ giữa giá trị của 2 biến.
Vị trí điểm đánh dấu là giá trị cho mỗi lần quan sát.
import matplotlib.pyplot as plt
x =[5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6]
y =[99, 86, 87, 88, 100, 86, 103, 87, 94, 78, 77, 85, 86]
plt.scatter(x, y, c ="blue")
# To show the plot
plt.show()
import matplotlib.pyplot as plt
# dataset-1
x1 = [89, 43, 36, 36, 95, 10, 66, 34, 38, 20]
y1 = [21, 46, 3, 35, 67, 95, 53, 72, 58, 10]
# dataset2
x2 = [26, 29, 48, 64, 6, 5, 36, 66, 72, 40]
y2 = [26, 34, 90, 33, 38, 20, 56, 2, 47, 15]
plt.scatter(x1, y1, c ="pink",linewidths = 2,marker ="s",edgecolor ="green",s = 50)
plt.scatter(x2, y2, c ="yellow",linewidths = 2,marker ="^",edgecolor ="red",s = 200)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
# Import the required modules
import matplotlib.pyplot as plt
import numpy as np
# Set figure size
plt.figure(figsize=(8,5))
# Create the data
countries =['Qatar','Luxembourg','Singapore','Brunei','Ireland','Norway','UAE','Kuwait']
populations = [2781682,
604245,5757499,428963,4818690,5337962,9630959,4137312]
gdp_per_capita = [130475, 106705, 100345, 79530, 78785, 74356,69382, 67000]
# scale GDP per capita income to shoot the bubbles in the graph
scaled_gdp_per_capita = np.divide(gdp_per_capita, 80)
colors = np.random.rand(8)
# Draw the scatter diagram
plt.scatter(countries, populations, s=scaled_gdp_per_capita, c=colors,
cmap="Blues",edgecolors="grey", alpha=0.5)
# Add X Label on X-axis
plt.xlabel("Countries")
# Add Y Label on X-axis
plt.ylabel("Population")
# Add title to graph
plt.title("Bubble Chart")
# rotate x label for clear visualization
plt.xticks(rotation=45)
# Show the plot
plt.show()
Hình ảnh hóa dữ liệu là một kỹ thuật mạnh mẽ để phân tích một tập dữ liệu lớn thông qua biểu diễn đồ họa. Python cung cấp các mô-đun khác nhau hỗ trợ việc biểu diễn dữ liệu bằng đồ họa. Các mô-đun được sử dụng rộng rãi là Matplotlib , Seaborn và Plotly . Và chúng ta có một mô-đun nữa tên là Squarify chủ yếu được sử dụng để vẽ Sơ đồ cây
#pip install squarify
n = titanic.groupby('class')[['survived']].sum()
n
| survived | |
|---|---|
| class | |
| First | 136 |
| Second | 87 |
| Third | 119 |
import seaborn as sns
import squarify
import matplotlib.pyplot as plt
titanic = sns.load_dataset('titanic')
a = titanic.groupby('class')[['survived']].sum().index.get_level_values(0).tolist()
d = titanic.groupby('class')[['survived']].sum().reset_index().survived.values.tolist()
squarify.plot(sizes=d,label=a, alpha=.8 )
plt.axis('off')
plt.show()
#!pip install wordcloud
#!pip install pillow
#!pip install matplotlib
# Importing Libraries
import pandas as pd
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
# Importing Dataset
df = pd.read_csv("Restaurant_Reviews.tsv", sep=" ")
#Creating the text variable
text = " ".join(cat for cat in df.Review)
# Generate word cloud
word_cloud = WordCloud(width=3000, height=2000, random_state=1, background_color="salmon", colormap="Pastel1",
collocations=False, stopwords=STOPWORDS,).generate(text)
# Display the generated Word Cloud
plt.imshow(word_cloud)
plt.axis("off")
plt.show()
Đồ thị ngăn xếp hình nêm là một trong những kỹ thuật trực quan hóa dữ liệu cho thấy dữ liệu phân cấp trong một hệ thống bán kính
import numpy as np
import matplotlib.pyplot as plt
# data from United Nations World Population Prospects (Revision 2019)
# https://population.un.org/wpp/, license: CC BY 3.0 IGO
year = [1950, 1960, 1970, 1980, 1990, 2000, 2010, 2018]
population_by_continent = {
'africa': [228, 284, 365, 477, 631, 814, 1044, 1275],
'americas': [340, 425, 519, 619, 727, 840, 943, 1006],
'asia': [1394, 1686, 2120, 2625, 3202, 3714, 4169, 4560],
'europe': [220, 253, 276, 295, 310, 303, 294, 293],
'oceania': [12, 15, 19, 22, 26, 31, 36, 39],
}
fig, ax = plt.subplots()
ax.stackplot(year, population_by_continent.values(),
labels=population_by_continent.keys(), alpha=0.8)
ax.legend(loc='upper left')
ax.set_title('World population')
ax.set_xlabel('Year')
ax.set_ylabel('Number of people (millions)')
plt.show()
Biểu đồ dòng là một loạt các biểu đồ khu vực xếp chồng lên nhau. Thay vì vẽ biểu đồ các giá trị theo trục y thông thường, đồ thị dòng sẽ cân bằng đường cơ sở của mỗi "ngăn xếp" để làm cho nó đồng đều quanh trục x.
Biểu đồ dòng là lý tưởng để hiển thị bộ dữ liệu khối lượng lớn, để tìm các mẫu và xu hướng trong một khoảng thời gian dài trên phạm vi phân loại rộng.
Ví dụ, các đỉnh và đáy theo mùa trong hình dạng dòng suối có thể thể hiện một ví dụ không liên tục.
Biểu đồ luồng cũng có thể được sử dụng để hình dung sự không ổn định đối với việc thu thập tài nguyên khổng lồ trong một khung thời gian cụ thể.
# Fixing random state for reproducibility
np.random.seed(19680801)
def gaussian_mixture(x, n=5):
"""Return a random mixture of *n* Gaussians, evaluated at positions *x*."""
def add_random_gaussian(a):
amplitude = 1 / (.1 + np.random.random())
dx = x[-1] - x[0]
x0 = (2 * np.random.random() - .5) * dx
z = 10 / (.1 + np.random.random()) / dx
a += amplitude * np.exp(-(z * (x - x0))**2)
a = np.zeros_like(x)
for j in range(n):
add_random_gaussian(a)
return a
x = np.linspace(0, 100, 101)
ys = [gaussian_mixture(x) for _ in range(3)]
fig, ax = plt.subplots()
ax.stackplot(x, ys, baseline='wiggle')
plt.show()
scipy.cluster.hierarchy.linkage(ndarray , method , metric , optimal_ordering)
Các bộ phận của Dendrogram • Các nhánh của dendrogram được gọi là Clades. Các nhóm này được sắp xếp theo mức độ giống nhau hoặc khác nhau của chúng. • Mỗi nhánh của cây chùm ngây có một hoặc nhiều lá. P, Q, R, S, T và U là các lá của biểu đồ dendrogram:
# Dendrogram thông thường
# Python program to plot the hierarchical
# clustering dendrogram using SciPy
# Import the python libraries
import numpy as np
from scipy.cluster import hierarchy
import matplotlib.pyplot as plt
# Create an array
x = np.array([100., 200., 300., 400., 500., 250.,450., 280., 450., 750.])
# Plot the hierarchical clustering as a dendrogram.
temp = hierarchy.linkage(x, 'single')
plt.figure()
dn = hierarchy.dendrogram(temp, above_threshold_color="green", color_threshold=.7)
# Dendrogram sử dụng hướng ngang
# Plot the dendrogram in horizontal orientation
# Import the python libraries
import numpy as np
from scipy.cluster import hierarchy
import matplotlib.pyplot as plt
# Create an array
x = np.array([100., 200., 300., 400., 500., 250.,450., 280., 450., 750.])
# Plot the hierarchical clustering as a dendrogram.
temp = hierarchy.linkage(x, 'single')
plt.figure()
dn = hierarchy.dendrogram(temp, above_threshold_color="green", color_threshold=.7, orientation='right')